﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;

namespace My_TV_Manager.Model
{
    public static class TVDB
    {
        private static string APIKey = "F2E749DAC0944AE5";
        private static string APIUrl = "http://www.thetvdb.com/api";
        private static string TVDBUrl = APIUrl + "/" + APIKey + "/series/";

        private static string GetSeriesUrl(int seriesID)
        {
            return TVDBUrl + seriesID.ToString() + "/all/en.xml";
        }

        public static int GetSeriesID(string seriesName)
        {
            string seriesUrl = APIUrl + "/GetSeries.php?seriesname=" + seriesName;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(seriesUrl);

            XmlNodeList seriesID = xmlDoc.GetElementsByTagName("seriesid");

            int id;
            if (int.TryParse(seriesID[0].InnerText, out id)) { return id; }
            return -1;
        }

        public static Series GetSeriesInfo(int seriesID)
        {
            string seriesUrl = GetSeriesUrl(seriesID);
            Console.Out.WriteLine(seriesUrl);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(seriesUrl);

            Series series = new Series(xmlDoc);

            return series;
        }

        public static Series GetSeriesInfo(string seriesName)
        {
            return GetSeriesInfo(GetSeriesID(seriesName));
        }

        public static List<int> GetSearchSeriesIDs(string searchName, Controller controller)
        {
            controller.ClearSearchResults();

            string searchUrl = APIUrl + "/GetSeries.php?seriesname=" + searchName;
            XmlDocument xmlDoc = new XmlDocument();
            try { xmlDoc.Load(searchUrl); }
            catch { return null; }

            XmlNodeList seriesIDs = xmlDoc.GetElementsByTagName("seriesid");

            List<int> results = new List<int>();
            int id;

            for (int i = 0; i < seriesIDs.Count; i++)
            {
                if (int.TryParse(seriesIDs[i].InnerText, out id)) { results.Add(id); }
            }

            return results;
        }

        public static bool GetSearchResultInfo(int seriesId, int relevance, 
                                               Controller controller)
        {
            if (controller.RestrictSearchResults &&
                controller.CurrentSearchResults.Count == controller.SearchResultLimit)
            {
                return false;
            }

            SearchResult result = GetSeriesSearchInfo(seriesId);
            if (result == null) { return false; }

            controller.AddSearchResult(result, relevance);
            return true;
        }

        public static SearchResult GetSeriesSearchInfo(int seriesId)
        {
            // Open the XML document
            string seriesUrl = GetSeriesUrl(seriesId);
            XmlDocument xmlDoc = new XmlDocument();
            try { xmlDoc.Load(seriesUrl); }
            catch (WebException) { return null; }

            // Get the necessary data for the search result
            string name;
            int startYear;
            double rating;
            int numRatings;
            Bitmap banner;

            // Get the series name from the XML document
            XmlNodeList nodeList = xmlDoc.GetElementsByTagName("SeriesName");
            if (nodeList.Count > 0 && nodeList[0].InnerText.Length > 0) 
            {
                name = nodeList[0].InnerText;
            }
            else 
            {
                if (Settings.IgnoreIncompleteSeries) { return null; }
                name = null; 
            }

            // Get the first aired date from the XML document
            nodeList = xmlDoc.GetElementsByTagName("FirstAired");
            if (nodeList.Count > 0 && nodeList[0].InnerText.Length > 0) 
            {
                startYear = int.Parse(nodeList[0].InnerText.Substring(0, 4)); 
            }
            else 
            {
                if (Settings.IgnoreIncompleteSeries) { return null; } 
                startYear = 0;
            }

            // Get the use rating from the XML document
            nodeList = xmlDoc.GetElementsByTagName("Rating");
            if (nodeList.Count > 0 && nodeList[0].InnerText.Length > 0) 
            {
                rating = double.Parse(nodeList[0].InnerText);        
            }
            else 
            {
                if (Settings.IgnoreIncompleteSeries) { return null; } 
                rating = 0.0;
            }

            // Get the use rating from the XML document
            nodeList = xmlDoc.GetElementsByTagName("RatingCount");
            if (nodeList.Count > 0 && nodeList[0].InnerText.Length > 0)
            {
                numRatings = int.Parse(nodeList[0].InnerText);
            }
            else
            {
                if (Settings.IgnoreIncompleteSeries) { return null; }
                numRatings = 0;
            }

            // Get the banner from the XML document
            nodeList = xmlDoc.GetElementsByTagName("banner");
            if (nodeList.Count > 0 && nodeList[0].InnerText.Length > 0) 
            {
                string url = "http://www.thetvdb.com/banners/" +
                             xmlDoc.GetElementsByTagName("banner")[0].InnerText;
                Stream imageStream = new WebClient().OpenRead(url);
                banner = (Bitmap)Image.FromStream(imageStream);
            }
            else 
            {
                if (Settings.IgnoreIncompleteSeries) { return null; } 
                banner = null;
            }

            return new SearchResult(name, seriesId, startYear, 
                                    rating, numRatings, banner);
        }
    }
}
